package com.jerei.web.utils;

import com.jerei.plugin.exceptions.PluginNotInstallException;
import ro.fortsoft.pf4j.*;
import ro.fortsoft.pf4j.spring.SpringExtensionFactory;

import java.io.File;
import java.util.List;

/**
 * Created by sunfeihu on 2016/11/22.
 */
public class UtilsPluginManager {

    private UtilsPluginManager() {

    }

    private static PluginManager springPluginManager = null;

    protected static void init(String folder) {
        File pluginsFolder = new File(folder);
        if (!pluginsFolder.exists()) {
            pluginsFolder.mkdir();
        }
        springPluginManager = new DefaultPluginManager(pluginsFolder) {
            @Override
            protected ExtensionFactory createExtensionFactory() {
                return new SpringExtensionFactory(this);
            }
        };
        springPluginManager.loadPlugins();
        springPluginManager.startPlugins();
    }

    public static PluginManager get() {
        return springPluginManager;
    }

    /**
     * 获取单个扩展点
     *
     * @param clzz     扩展功能接口
     * @param pluginId 插件ID
     * @param <T>      扩展接口类型
     * @return 插件扩展点
     */
    public static <T> T getExtension(Class<T> clzz, String pluginId) throws PluginNotInstallException {
        PluginWrapper pluginWrapper = springPluginManager.getPlugin(pluginId);
        if (pluginWrapper == null) {
            return null;
        }
        List<T> extensions = springPluginManager.getExtensions(clzz, pluginId);
        if (null != extensions && extensions.size() == 1) {
            return extensions.get(0);
        } else {
            throw new PluginNotInstallException();
        }
    }

    /**
     * 获取扩展点集合
     *
     * @param clzz     扩展功能接口
     * @param pluginId 插件ID
     * @param <T>      扩展接口类型
     * @return 插件扩展点集合
     */
    public static <T> List<T> getExtensions(Class<T> clzz, String pluginId) {
        PluginWrapper pluginWrapper = springPluginManager.getPlugin(pluginId);
        if (pluginWrapper == null) {
            return null;
        }
        if (!pluginWrapper.getPluginState().equals(PluginState.CREATED) && !pluginWrapper.getPluginState().equals(PluginState.STARTED)) {
            return null;
        }
        return springPluginManager.getExtensions(clzz, pluginId);
    }

}